//
//  HomeViewController.m
//  MK
//
//  Created by Le Quang Vinh on 8/10/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "HomeViewController.h"
#import "AudioStreamer.h"

@interface HomeViewController ()

@end

@implementation HomeViewController
@synthesize progressBar;
@synthesize playButton;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"Home";
    // Do any additional setup after loading the view from its nib.
    [self playSongWithUrl:@"http://media.vpop.vn:8080/vpop/medias//hatt89/NhacRock/VariousArtists/6b9aa5199d5b57b006206ca37597ef76.mp3"];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark- AudioStreamer
//
// createStreamer
//
// Creates or recreates the AudioStreamer object.
//
- (void)createStreamer:(CFStringRef)urlString
{
	if (streamer)
	{
		return;
	}
    
	[self destroyStreamer];
	
	NSString *escapedValue =
    [(NSString *)CFURLCreateStringByAddingPercentEscapes(
                                                         nil,
                                                         urlString,
                                                         NULL,
                                                         NULL,
                                                         kCFStringEncodingUTF8)
     autorelease];
    
	NSURL *url = [NSURL URLWithString:escapedValue];
	streamer = [[AudioStreamer alloc] initWithURL:url];
	
	progressUpdateTimer =
    [NSTimer
     scheduledTimerWithTimeInterval:0.1
     target:self
     selector:@selector(updateProgress:)
     userInfo:nil
     repeats:YES];
	[[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(playbackStateChanged:)
     name:ASStatusChangedNotification
     object:streamer];
}

//
// destroyStreamer
//
// Removes the streamer, the UI update timer and the change notification
//
- (void)destroyStreamer
{
	if (streamer)
	{
		[[NSNotificationCenter defaultCenter]
         removeObserver:self
         name:ASStatusChangedNotification
         object:streamer];
		[progressUpdateTimer invalidate];
		progressUpdateTimer = nil;
		
		[streamer stop];
		[streamer release];
		streamer = nil;
	}
}

- (void) playSongWithUrl:(NSString *)songUrl
{
    [self destroyStreamer];
    [self createStreamer:(CFStringRef)songUrl];
    [streamer start];
}

//
// updateProgress:
//
// Invoked when the AudioStreamer
// reports that its playback progress has changed.
//
- (void)updateProgress:(NSTimer *)updatedTimer
{
	if (streamer.bitRate != 0.0)
	{
		double progress = streamer.progress;
		double duration = streamer.duration;
		
		if (duration > 0)
		{
            //			[positionLabel setText:
            //             [NSString stringWithFormat:@"Time Played: %.1f/%.1f seconds",
            //              progress,
            //              duration]];
			[progressBar setEnabled:YES];
			[progressBar setValue:progress / duration];
		}
		else
		{
			[progressBar setEnabled:NO];
		}
	}
	else
	{
		//positionLabel.text = @"Time Played:";
	}
}

//
// playbackStateChanged:
//
// Invoked when the AudioStreamer
// reports that its playback status has changed.
//
- (void)playbackStateChanged:(NSNotification *)aNotification
{
	if ([streamer isWaiting])
	{
		playButton.titleLabel.text = @"Play";
        [playButton setImage:[UIImage imageNamed:@"loadingbutton.png"] forState:UIControlStateNormal];
	}
	else if ([streamer isPlaying])
	{
		playButton.titleLabel.text = @"Pause";
        [playButton setImage:[UIImage imageNamed:@"pausebutton.png"] forState:UIControlStateNormal];
	}
	else if ([streamer isIdle])
	{
		[self destroyStreamer];
		playButton.titleLabel.text = @"Play";
        [playButton setImage:[UIImage imageNamed:@"stopbutton.png"] forState:UIControlStateNormal];
	}
}


- (IBAction)onPlayButtonTouched
{
    if([streamer isPlaying])
    {
        playButton.titleLabel.text = @"Play";
        [playButton setImage:[UIImage imageNamed:@"playbutton.png"] forState:UIControlStateNormal];
    }
    if([streamer isPaused])
    {
        playButton.titleLabel.text = @"Pause";
        [playButton setImage:[UIImage imageNamed:@"pausebutton.png"] forState:UIControlStateNormal];

    }
    [streamer pause];
}

//
// sliderMoved:
//
// Invoked when the user moves the slider
//
// Parameters:
//    aSlider - the slider (assumed to be the progress slider)
//
- (IBAction)sliderMoved:(UISlider *)aSlider
{
	if (streamer.duration)
	{
		double newSeekTime = (aSlider.value) * streamer.duration;
		[streamer seekToTime:newSeekTime];
	}
}

@end
